﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

using LeanEngine.Extensions;

namespace LeanEngine.Validation
{
    /// <summary>
    /// Represents the cache validation of the attributes present in a property.
    /// </summary>
    public static class ValidatorMetadataCache
    {
        private static Dictionary<PropertyInfo, List<ValidationAttribute>> cache = new Dictionary<PropertyInfo, List<ValidationAttribute>>();

        /// <summary>
        /// Returns the list of validation attributes contained in the property.
        /// </summary>
        /// <exception cref="System.ArgumentNullException"></exception>
        /// <param name="property">The property that contains the attributes of validation.</param>
        public static List<ValidationAttribute> GetValidatorList(PropertyInfo property)
        {
            if (property.IsNull()) throw new ArgumentNullException("property");

            lock (cache)
            {
                if (!cache.ContainsKey(property))
                {
                    var customAttributesList = property.GetCustomAttributes(false);
                    var list = new List<ValidationAttribute>(customAttributesList.Length);

                    for (int i = 0; i < customAttributesList.Length; i++)
                    {
                        var validationAttribute = customAttributesList[i] as ValidationAttribute;
                        if (validationAttribute.IsNotNull())
                        {
                            list.Add(validationAttribute);
                        }
                    }

                    cache.Add(property, list);

                    return list;
                }
            }

            return cache[property];
        }
    }
}
